﻿using MailManagementWebService.Model.Responses;
using MailManagementWebService.Model.Requests;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;

namespace MailManagementWebService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class MailService : IMailService
    {
        public Stream GetMails(string keyWords)
        {
            throw new NotImplementedException();
        }

        public string GetMailInfo(string keyWords)
        {
            throw new NotImplementedException();
        }

        [WebInvoke(UriTemplate = "/", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        public PostResponse PostRequest(Stream postData)
        {
            PostResponse resp = new PostResponse();
            string postedValue = RetrievePostedValue(postData);
            PostRequest request = new JavaScriptSerializer().Deserialize<PostRequest>(postedValue);  
            try
            {
                switch(request.MethodName.ToLower())
                {
                    case "postmail":

                        break;
                }
            }
            catch(Exception ex)
            {
                resp.ErrorMsg = ex.Message;
                resp.HasError = true;
                resp.ResponseData = null;
                resp.CheckTime = System.DateTime.Now.ToShortTimeString();
            }
            return resp;
        }

        private string RetrievePostedValue(Stream postData)
        {
            StreamReader reader = new StreamReader(postData);
            string queryStr = reader.ReadToEnd();
            NameValueCollection queryArray = HttpUtility.ParseQueryString(queryStr);
            return queryArray[0];
        }
    }
}
